<?php if(!defined('MS_XTIGER')) exit('Access Denied');
/**
 * Created by openXtiger.org.
 * User: xtiger
 * Date: 2009-5-16
 * Time: 11:57:17
 */
/**
 * parse template
 *
 * @param string $tplfile  template file
 * @param string $objfile  cache file
 * @return
 */

function _xtf_parse_template($tplfile, $objfile, $langdir, $viewdir) {
    $xl = array();
	if(!$fp = @fopen($tplfile, 'r')) {
        exit('Template file :<br>'.srealpath($tplfile).'<br>Not found or have no access!');
    }

    
    $template = fread($fp, filesize($tplfile));
    fclose($fp);
    $template = str_replace('<?php exit?>', '', $template);


    $template = preg_replace("/<\!\-\-\{&&(.+?)\}\-\->(.*?)<\!\-\-\{\/&&\}\-\->/se","_xtf_read(\$viewdir,'\\1','\\2')", $template); //require views
    $template = preg_replace("/<\!\-\-\{&(.+?)\}\-\->/e","_xtf_read(\$viewdir,'\\1')", $template); //require views
     // //parse
	$template = preg_replace("/<\!\-\-\/\*(.+?)\*\/\-\->/s", "", $template); // <!-/*-->  <!--*/-->
	
    //<!--{!# }-->
    $matches = array();
    if(preg_match("/\{\!\#(.+?)\}/", $template, $matches)) {
        foreach(explode(',',$matches[1]) as $v) {
            if(file_exists(MS_APPPATH.$langdir.$v.'.lang.php')) {
                include_once(MS_APPPATH.$langdir.$v.'.lang.php');
                if(function_exists('xt_'.$v.'_lang')) {
                    $r = call_user_func('xt_'.$v.'_lang');
                    $xl = array_merge(is_array($r)?$r:array($r),$xl); 
                }
            }
        }
    }


    $template = preg_replace("/<\!\-\-\{\!\#.+?\}\-\->/", "", $template); // <!--{!# }-->
    $template = preg_replace("/<\!\-\-\{\!\&(.+?)\}\-\->/e", "xtf_includelang(\$langdir,'\\1')", $template); // <!--{!& }-->

	$template = preg_replace_callback("/<\!\-\-\{\{(.+?)\}\}\-\->/s", '_xtf_xpt', $template); // macro


	$var_regexp = "\\\$\{(.*?)(&)?\}"; //var,array
	$const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)"; //const

	$template = preg_replace("/([\n\r]+)\t+/s", "\\1", $template); // remove /t
	$template = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template); //change <!--{}--> to {}

    $template = preg_replace("/\{\!\@(.*?)\}/e", "xtf_language(\$xl,'$1')", $template);

	$template = str_replace("{LF}", "<?php echo \"\\n\"?>", $template);

	/*$template = preg_replace("/(\\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\.([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/s", "\\1['\\2']", $template);*/
    $template = preg_replace("/xtv=\"([^\"]*)\"/", "\\1", $template);
    $template = preg_replace_callback("/<(input|option)([^>]*?)xtc=\"([^\"]*)\"/", "_xtf_check", $template);

    $template = preg_replace("/<(img|a|form|link|script|input)([^>]*?(?:src|action|href))\\s*?=([\"'])?\\s*?([^>]*?)\\3/ie", "_xtf_uri('\\1','\\2','\\3','\\4')", $template);
    //$template = preg_replace("/(?<=url\()([^\)]*?)/e", "xt_static_uri('\\1')", $template);
    $template = preg_replace("/\#\{(.*?),?([^,]*?)\}\#/ei", "_xtf_uri_auth('\\2','\\1')", $template);

    $template = preg_replace("/(?<!\\\$)\{\!(.+?)\}/e", "_xtf_static_lang(\$xl,'$1')", $template);
	$template = preg_replace("/$var_regexp/e", "_xtf_var('\\1','\\2')", $template);


	$template = ltrim($template);
	$template = "<?php if(!defined('MS_XTIGER')) exit('Access Denied'); \$_XT_LANG=array();?>$template";
	$template = preg_replace("/[\n\r\t]*\{\#\s*(.+?)\}[\n\r\t]*/is", "\n<?php include xtf_template(\"\\1\"); ?>\n", $template);
	$template = preg_replace("/[\n\r\t]*\{elseif\s+(.+?)\}[\n\r\t]*/is", "\n<?php } elseif(\\1) { ?>\n", $template);
	$template = preg_replace("/[\n\r\t]*\{else\}[\n\r\t]*/is", "\n<?php } else { ?>\n", $template);

	for($i = 0; $i < 5; $i++) {
		$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+?)([<>=]+)(\S+)\s+(\S+?)([+-].*?)\}[\n\r]*(.+?)[\n\r]*\{(?:pool|\/loop)\}[\n\r\t]*/is", "<?php for(\\4=\\1;\\4\\2\\3;\\4\\5) { ?>\n\\6\n<?php }?>\n", $template);
		$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\}[\n\r]*(.+?)[\n\r]*\{(?:pool|\/loop)\}[\n\r\t]*/is", "<?php if(isset(\\1) && is_array(\\1)) { \\2_index=0;foreach(\\1 as \\2) { \\2_index++;?>\n\\3\n<?php } } ?>\n", $template);
		$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}[\n\r\t]*(.+?)[\n\r\t]*\{(?:pool|\/loop)\}[\n\r\t]*/is", "<?php if(isset(\\1) && is_array(\\1)) { \\2_index=0;foreach(\\1 as \\2 => \\3) { \\2_index++;?>\n\\4\n<?php } } ?>\n", $template);
		$template = preg_replace("/[\n\r\t]*\{if\s+(.+?)\}[\n\r]*(.+?)[\n\r]*\{(?:fi|\/if)\}[\n\r\t]*/is", "<?php if(\\1) { ?>\n\\2\n<?php } ?>\n", $template);
	}
	
	$template = preg_replace("/\{get\s+([^}]+)\}(.*?)(?:\{teg\}|\{\/get\})/ise", "_xtf_get_parse('\\1','\\2')", $template);
	//$template = preg_replace("/(['\"])\S+?#\{(.*?),?([^,]*?)\}#.*?\\1/e", "_xtf_uri('\\1','\\2','\\3')", $template);
	$template = preg_replace("/<\/form>/", "<input type=\"hidden\" name=\"xt_formhash\" value=\"{XT_FORMHASH}\" />\n</form>", $template);
	$template = preg_replace("/\{$const_regexp\}/s", "<?php echo \\1?>", $template);
	$template = preg_replace("/ \?\>[\n\r]*\<\? /s", " ", $template);
	$template = preg_replace("/[\n\r\t]*\{@(.+?)@\}[\n\r\t]*/is", "<?php \\1 ?>", $template);
	$template = preg_replace("/[\n\r\t]*\{\=(.+?)\}[\n\r\t]*/is", "<?php echo \\1; ?>", $template);
	$template = preg_replace("/xtp=\"([^\"]*)\"/e", "_xtf_xpt_v('\\1')", $template);



	//write
	$template = trim($template);
	if(!empty($template)) {
		$needwrite = false;
		if(file_exists($objfile) && @unlink($objfile)) {
			xt_writefile($objfile.'.tmp', $template, 'text', 'w', 0);
			if(@rename($objfile.'.tmp', $objfile)) {
				$needwrite = false;
			} else {
				$needwrite = true;
			}
		} else {
			$needwrite = true;
		}
		//wirte second
		if($needwrite) xt_writefile($objfile, $template, 'text', 'w', 0);
	}
}
function _xtf_read($viewdir,$m,$body='') {
    global $_XC;
    $key = explode(',',$m);
    if($body) $key[] = str_replace('\"','"',$body);
    if(($idx = strpos($key[0],'.')) !== FALSE ) {
        $viewfile = $viewdir .$key[0];
    } else{
        $ext = empty($_XC['view_ext']) ? '.html.php' : $_XC['view_ext'];
        $viewfile = $viewdir.$key[0].$ext;
    }
    if(!$fp = @fopen($viewfile, 'r')) {
        return '';
    }
    $template = fread($fp, filesize($viewfile));
    fclose($fp);
    $template = str_replace('<?php exit?>', '', $template);
    if(count($key)>1){
        $c = count($key);
        for($i=1;$i<$c;$i+=2){
            $template = str_replace($key[$i], $key[$i+1], $template);          
        }
    }
    $template = preg_replace("/<\!\-\-\{&(.+?)\}\-\->/e","_xtf_read(\$viewdir,'\\1')", $template);
    return $template;
}
function _xtf_constant($m) {
    if(defined($m[1])) {
       return constant($m[1]);
    }
    return $m[1];
}
function _xtf_replace_constant($str) {
    return preg_replace_callback("/^(MS_.*?)\//","_xtf_constant",$str);
}
function _xtf_check($m){
    $m[3] = trim($m[3]);        
    return "<$m[1]$m[2]<?php echo $m[3]?'".($m[1] == 'option'?'selected="selected"':'checked="checked"')."':''?>";
}
function _xtf_get_parse($str, $end) {
    $end = str_replace('\"','"',$end);
    $matches =  $r = array();
    preg_match_all("/([a-z]+)\=\"([^\"]+)\"/i", stripslashes($str), $matches, PREG_SET_ORDER);
	foreach($matches as $v) {
		$r[$v[1]] = $v[2];
	}
	extract($r);
	if(!isset($dbsource)) $dbsource = '';
	if(!isset($fields)) $fields = '';
	if(!isset($sql)) $sql = '';
	if(!isset($ordersql)) $ordersql = '';
	if(!isset($rows)) $rows = 0;
	if(!isset($distinctfield)) $distinctfield = '';
	if(!isset($return) || !preg_match("/^\w+$/i", $return)) $return = 'r';
	$sql = "SELECT $fields FROM  $sql";
	if(isset($page)) {
	    return "<?php \$ARRAY = get('$sql','$ordersql', $rows, $page,  '$dbsource','$distinctfield');\${$return}_data=\$ARRAY['data'];\$pagectrl=\$ARRAY['pagectrl'];foreach(\${$return}_data as \${$return}_n=>\${$return}){\${$return}_n++;?>$end<?php } unset(\${$return}_data);?>";
	} else {
		return substr($str, -1) == '/' ? "<?php \${$return} = get('$sql','$ordersql', -1, 0,'$dbsource');?>" : "<?php \${$return}_data = get('$sql','$ordersql', $rows, 0, '$dbsource');foreach(\${$return}_data as \${$return}_n => \${$return}) { \${$return}_n++;?>$end<?php } unset(\${$return}_data);?>";
	}
}
function xtf_language($lang,$x){
    if(!empty($x)) {
        $r = '<?php $_XT_LANG=array_merge(array(';
        $d = '';
        foreach(explode(',',$x) as $v) {
            
            $r.="$d'$v'=>'".str_replace("'","\'",xt_lang($lang,$v))."'";
            $d = ',';
        }
        $r.= '),$_XT_LANG); ?>';
        return $r;
    }
    return '';
}
function xtf_includelang($langdir,$lang){
    foreach(explode(',',$lang) as $v) {
        if(file_exists(MS_APPPATH.$langdir.$v.'.lang.php')) {
            include_once(MS_APPPATH.$langdir.$v.'.lang.php');
            if(function_exists('xt_'.$v.'_lang')) {
                return "<?php include_once MS_APPPATH.'$langdir$v.lang.php';  \$_XT_LANG=array_merge(xt_{$v}_lang(),\$_XT_LANG);?>";
            }
        }
    }
    return '';   
}

function _xtf_static_lang($map, $key)  {
    if(empty($key)) return '';
    $key = explode(',',$key);
    $v = array_key_exists($key[0],$map) ? $map[$key[0]] : '!'.$key[0].'!';
    if(count($key)>1) {
        return preg_replace("/\{(\d*)\}/e","_xtf_static_klang(\$key,'\\1')",$v);      
    }
    if(preg_match("/\{\\\$[^\}]*\}/",$v)) {
        return '<?php echo "'.str_replace('"','\"',$v).'" ?>';
    }
    return $v;
}
function _xtf_static_klang($key,$k){
    return isset($key[$k])?$key[$k]:'';
}
function _xtf_uri_auth($uri='',$namespace='') {
    if(substr($uri,0,1)=='@'){
        $uri = substr($uri,1);
        return xt_uri($uri,$namespace).'\',\''.xt_auth(trim($namespace,'/').'/'.trim($uri,'/'));
    }
    return xt_uri($uri,$namespace);
}
function _xtf_uri($p1, $p2, $p3,$p4) {
    $p1 = strtolower($p1);
    $p2 = str_replace('\"','"',$p2);
    $p3 = str_replace('\"','"',$p3);
    //echo $p1.','.$p2.','.$p3.','.$p4.'<br/>';

    $p1 = str_replace('\"','"',$p1);
    $p2 = str_replace('\"','"',$p2);
    //echo $p3.'<br/>';
    /*if(substr($p4,0,2)=='#@') {
        $p4 = substr($p4,2);
        if(!xt_auth(substr($p4,2))) return "<$p1";
    }*/
    $matches = array();
    if (substr($p4,0,10) != 'javascript') {
        if(preg_match("/\S*?\#\{(.*?),?([^,]*?)\}\#/", $p4, $matches)) {
            $p4 = xt_uri($matches[2],$matches[1]);
        }else if($p4=='#'){
        }else if(substr($p4,0,2)=='##' || substr($p4,-2)=='##') {
            $p4 = trim($p4,'#');
        } else {
            $p4 = xt_static_uri($p4);
        }
    }
    return "<$p1$p2=$p3$p4$p3";
}
/**
 *
 * add quote for array
 * @param string $var
 * @return
 */
function _xtf_var($var,$g) {
    $var = preg_replace("/(\\$[!2a-zA-Z_][a-zA-Z0-9_]*)\[(\\\\\")?([a-zA-Z_][a-zA-Z0-9_\-\.]+)(\\2)?\]/", "\\1['\\3']", preg_replace("/@\((.*?)\)/",'{$\\1}','$'.trim($var)));
    $var = preg_replace("/\{\\\$\!(2)?([^\}]*)\}/","\".xt_lang\\1(\$_XT_LANG,\$\\2,\$_XH_D).\"",$var);
    $m = array();
    if(preg_match("/(\\$[!2a-zA-Z_][a-zA-Z0-9_]*?(\['[a-zA-Z0-9_\-\.]+'\])?)(\!{1,2}|\?{1,2})([^!]*)(.*)/", $var, $m)) {
        $v = preg_replace("/\\\$\!(2)?(.*)/","xt_lang\\1(\$_XT_LANG,\$\\2,\$_XH_D)",$m[1]);
        $m[1] = preg_replace("/\\\$\!(2)?(.*)/","\$\\2",$m[1]);
        $mp = $m[3]=='!' || $m[3]=='!!'?$m[4]:substr($m[5],1);
        if($g) $g =" global $m[1];";
        return ($m[3]=='??' || $m[3]=='!!'?"<?php $g echo isset($m[1]) && !empty($m[1])":"<?php $g echo isset($m[1])").'?'.(empty($m[4])? $v : ("\"$m[4]\"")).":\"".$mp."\"?>";
    }
    $var = preg_replace("/\\\$\!(2)?(.*)/","xt_lang\\1(\$_XT_LANG,\$\\2,\$_XH_D)",$var);
    if($g) $g =" global $var;";
    return "<?php $g echo $var?>";
}

function _xtf_xpt($m) {
    global $__xtps;
    $var = $m[1];
    $v = str_replace("\\\"", "\"",trim($var));
    $r = preg_split('/(xtp_[\d]+?):/',$v,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    for($i=0;$i<count($r);$i=$i+2) {
        $__xtps[$r[$i]] = $r[$i+1];
    }
    return "";
}
function _xtf_xpt_v($var){
    global $__xtps;
    $key = explode(',',$var);
    if(count($key)>1){
        $c = count($key);
        $var = $__xtps['xtp_'.$key[0]];
        for($i=1;$i<$c;$i++){
            $var = str_replace('{'.$i.'}', $key[$i], $var);
        }
        return '<?php '.$var.' ?>';
    }
    return '<?php '.$__xtps['xtp_'.$var].' ?>';
}
/**
 *
 *
 * @param string $expr
 * @return
 */
function _xtf_striptagquotes($expr) {
	$expr = preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr);
	$expr = str_replace("\\\"", "\"", preg_replace("/\[\'([a-zA-Z0-9_\-\.\x7f-\xff]+)\'\]/s", "[\\1]", $expr));
	return $expr;
}

/**
 *
 * @param string $var
 * @return
 */
/*function _xtf_languagevar($m, $lang) {
	return xt_hashmap($lang,$m);
}*/

/**
 *
 *
 * @param string $cachekey
 * @param string $parameter
 * @return
 */
function _xtf_blocktags($cachekey, $parameter) {
	return striptagquotes("<?php block(\"$cachekey\", \"$parameter\"); ?>");
}

function _xtf_replacevars($v) {
    global $_XH_D,$_XC;
    return empty($_XH_D[$v]) ? $_XC[$v] : $_XH_D[$v];
}

?>